#include "TcpServer.h"
#include <iostream>

using std::cout;
using std::endl;

TcpServer::TcpServer(const string &ip, unsigned short port, size_t subReactorNum)
: _loop()
, _acceptor(&_loop, ip, port)
, _threadPool(&_loop, subReactorNum) // 创建线程池，假设使用4个线程
{
}

TcpServer::~TcpServer()
{
}

void TcpServer::start()
{
    _acceptor.setNewConnectionCallback(
        std::bind(&TcpServer::onNewConnection, this, std::placeholders::_1));
    _acceptor.ready(); // 准备好Acceptor
    _threadPool.start(); 
    _loop.setMainLoop(&_acceptor); // 设置主Reactor
    _loop.loop();
}

void TcpServer::stop()
{
    _loop.unloop();
}

void TcpServer::setAllCallback(TcpConnectionCallback &&cb1,
                               TcpConnectionCallback &&cb2,
                               TcpConnectionCallback &&cb3)
{
    _loop.setNewConnectionCallback(std::move(cb1));
    _loop.setMessageCallback(std::move(cb2));
    _loop.setCloseCallback(std::move(cb3));
}

void TcpServer::onNewConnection(int connfd)
{
    // _loop.handleNewConnection(listenfd, connfd);

    //将新连接分配给不同的EventLoop
    EventLoop *ioLoop = _threadPool.getNextLoop();

    ioLoop->runInLoop([this, connfd, ioLoop]() {
        ioLoop->handleNewConnection(connfd);
    });
}

void TcpServer::removeConnection(const TcpConnectionPtr &conn)
{
    _loop.runInLoop([this, conn]() {
        _loop.removeConnection(conn);
    });
}